package rest_cl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient { 
	public String execute(String targetURL, String method, String payload)
		throws Exception
	{
		URL url;
		HttpURLConnection connection = null;  
		boolean wentThrough=false;
		String response_="";
		try {
			System.out.println("payload"+payload);
			//Create connection
			url = new URL(targetURL);
			connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod(method);
			connection.setRequestProperty("Content-Type", "application/octet-stream");

			connection.setUseCaches (false);
			connection.setDoInput(true);
			if (payload!=null) {
				connection.setDoOutput(true);
				DataOutputStream wr = new DataOutputStream (
						connection.getOutputStream ());
				wr.writeBytes (payload);
				wr.flush ();
				wr.close ();
			} 
			else{
				connection.connect();
			}

			//Get Response	
			// System.out.println(connection.getResponseCode());
			InputStream is;
			try{
				is = connection.getInputStream();
				wentThrough=true;
			}catch(Exception e){
				is = connection.getErrorStream();
				wentThrough=false;
			}
			
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line;
			StringBuffer response = new StringBuffer(); 
			while((line = rd.readLine()) != null) {
				response.append(line+"\n");
			}
			response_ = response.toString();
			rd.close();			
		} catch (Exception e) {
			e.printStackTrace();			
		} finally {
			if(connection != null) {
				connection.disconnect(); 
			}			
		}
		
		if (wentThrough==true){
			return response_;
		}else{
			throw new Exception(response_);
		}		
	}

	
	public static boolean executePost(String targetURL, String urlParameters)
	{
		URL url;
		HttpURLConnection connection = null;  
		boolean wentThrough=false;
		try {
			//Create connection
			url = new URL(targetURL);
			connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", 
			"application/octet-stream");

			//connection.setRequestProperty("Content-Length", "" + 
			//		Integer.toString(urlParameters.getBytes().length));
			// connection.setRequestProperty("Content-Language", "en-US");  

			connection.setUseCaches (false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			//Send request
			DataOutputStream wr = new DataOutputStream (
					connection.getOutputStream ());
			wr.writeBytes (urlParameters);
			wr.flush ();
			wr.close ();

			//Get Response	
			// System.out.println(connection.getResponseCode());
			InputStream is;
			try{
				is = connection.getInputStream();
				wentThrough=true;
			}catch(Exception e){
				is = connection.getErrorStream();
				wentThrough=false;
			}
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line;
			StringBuffer response = new StringBuffer(); 
			while((line = rd.readLine()) != null) {
				response.append(line);
				response.append('\r');
			}
			// System.out.println(response.toString());
			rd.close();
			//return response.toString();			
		} catch (Exception e) {
			e.printStackTrace();			
		} finally {
			if(connection != null) {
				connection.disconnect(); 
			}
			
		}
		return wentThrough;
	}

	public String executeGet(String desiredUrl)	 
	{
		URL url = null;
		BufferedReader reader = null;
		StringBuilder stringBuilder;

		try
		{
			// create the HttpURLConnection
			url = new URL(desiredUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			// just want to do an HTTP GET here
			connection.setRequestMethod("GET");

			// uncomment this if you want to write output to this url
			//connection.setDoOutput(true);

			// give it 15 seconds to respond
			connection.setReadTimeout(15*1000);
			connection.connect();

			// read the output from the server
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			stringBuilder = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null)
			{
				stringBuilder.append(line + "\n");
			}
			return stringBuilder.toString();
		}
		catch (Exception e)
		{
			// e.printStackTrace();	      
		}
		finally
		{
			// close the reader; this can throw an exception too, so
			// wrap it in another try/catch block.
			if (reader != null)
			{
				try
				{
					reader.close();
				}
				catch (IOException ioe)
				{
					ioe.printStackTrace();
				}
			}	 			
		}
		return null;
	}

	public static void main(String[] args) {		
		RestClient r=new RestClient();
		 String res=r.executeGet("http://localhost:9998/znodes/v1/");
//		boolean res=r.executePost("http://localhost:9998/znodes/v1/?op=create&name=cluster909998&dataformat=utf8",
//				"data");
		// -d "data1" -H'Content-Type: application/octet-stream' -w "\n%{http_code}\n" 
		// http://localhost:9998/znodes/v1?op=create&name=test&dataformat=utf8
		System.out.println(res); 		
	}

}
